package v2.parser.cli


import java.io.{OutputStreamWriter, BufferedWriter, Writer, File}
import util.parsing.input.{CharSequenceReader}
import v2.parser.tree.{TypedTree, NodeCrud}
import v2.parser.{Type, Literal}
import v2.parser.load.Loader
/**
 * @author bweber
 * @version $Rev$, $Date$
 */

trait Quotable {
  var str:String = null
  def quote() = { "\"" + str + "\"" } // todo escape quotes?
  def unquote() = { str.substring(1,str.length-1) } // todo unescape quotes?
}

object CLIMain extends Application {
  new CLI().main(List[String]().toArray)
}

class CLI {
  var commandParser:Commands = null
  var tree:NodeCrud = null
  
  def main(args:Array[String]) {
    // if passed file, load it
    if ( ! args.isEmpty ) {
      tree = NodeCrud(Loader(args(0)).currentTree)
    }
    else {
      if ( new File(".typed-tree").exists() ) {
        tree = NodeCrud(Loader().currentTree)
      }
      else {
        tree = NodeCrud(TypedTree("root",Literal("empty",Type("str"))))
      }
    }
    commandParser = new Commands(tree)
    var result = ""
    val writer = new OutputStreamWriter(System.out)
    while ( result != null ) {
      try {
        result = processCommands(writer)
      }
      catch {
        case e:Exception =>
          println("error: " + e.getMessage)
      }
    }
  }
  
  def processCommands(writer:Writer):String = {
    print(">>")
    val line = readLine()
    if ( line.trim().equals("exit") || line.trim().equals("quit") ) {
      return null
    }
    else {
      println("read line " + line)
      commandParser.parseMore(new CharSequenceReader(line),writer)
      writer.write("\n")
      writer.flush
      return line
    }
  }
}